<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" />
        <!-- 树形组件 -->
        <el-tree ref="tree" node-key="id" :highlight-current="true" :expand-on-click-node="false" :data="depts" :props="defaultProps" default-expand-all @current-change="selectNodeChange" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <template>
          <el-table :data="list">
            <el-table-column label="头像" align="center">
              <template #default="{ row }">
                <img v-if="row.staffPhoto" :src="row.staffPhoto" alt="" style="width: 30px;height: 30px;border-radius: 50%;">
                <span v-else class="username">{{ row.username?.charAt(0) }}</span>

              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="手机号" prop="mobile" sortable />
            <el-table-column label="工号" prop="workNumber" sortable />
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                <span> {{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 0 ? '非正式' : '无' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" prop="timeOfEntry" sortable />
            <el-table-column label="操作" width="280">
              <template #default="{ row }">
                <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
                <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delEmployee(row.id)">
                  <el-button slot="reference" type="text" size="mini" style="margin-left: 10px;">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>

          </el-table>
        </template>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height: 60px;" align="middle">
          <el-pagination
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            @current-change="changePage"
          />
        </el-row>

      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getDepartmentList" />
    <!-- 角色弹窗 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色" width="50%">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="confirm">确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { translateListToTree } from '@/utils'
import { getRoleListOfEnable } from '@/api/role'
import { getEmployeeList, exportEmployee, delEmployee, getEmployeeDetail, assignRoles } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 员工查询的参数对象
      queryParams: {
        page: 1,
        pagesize: 10,
        keyword: '',
        departmentId: null // 部门id
      },
      list: [],
      total: 0,
      showExcelDialog: false,
      showRoleDialog: false,
      roleIds: [], // 角色id
      roleList: [], // 角色列表
      currentUserId: null
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 获取部门列表
    async getDepartmentList() {
      const res = await getDepartmentList()
      // console.log(res)
      this.depts = translateListToTree(res, 0)
      // 记录部门中的首个节点
      // TODO (1) 默认选中高亮 (2) 拿着首个部门id,发请求，渲染右侧列表的数据
      this.queryParams.departmentId = this.depts[0].id
      // console.log(this.depts)
      // 设置首个节点的选中状态
      // 树形组件的渲染是异步的
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 选中节点 改变
    selectNodeChange(node) {
      // console.log(node.id)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      // console.log(rows, total)
      this.list = rows
      this.total = total
    },
    // 改变页数
    changePage(page) {
      // console.log(page)
      this.queryParams.page = page
      this.getEmployeeList()
    },
    // 导出员工
    async exportExcel() {
      const res = await exportEmployee()
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 删除员工
    async delEmployee(id) {
      // console.log(id)
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    // 获取已启用的角色列表
    async btnRole(id) {
      // this.showRoleDialog = true
      // 1. 获取已启用的角色列表
      const res = await getRoleListOfEnable()
      // 2. 视图渲染
      this.roleList = res
      // 3. 获取到员工所拥有的角色信息 - 根据员工的id
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      // 4. 复制给选中的角色列表（目的：为了保证渲染完成之后，再显示）
      this.roleIds = roleIds
      // 注意点：调用弹层显示时机
      this.showRoleDialog = true
    },
    // 确认分配
    async confirm() {
      await assignRoles({
        // 员工id
        id: this.currentUserId,
        // 角色id数组
        roleIds: this.roleIds
      })
      this.$message.success('角色分配成功')
      this.showRoleDialog = false
    },
    // 取消
    cancel() {
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
